/**
 * @file
 * @author dousha
 * @date 2020/11/30.
 */

#include "convert.h"

uint16_t get_u16(const uint8_t *bytes) {
	uint16_t out = 0;
	out |= bytes[0];
	out <<= 8u;
	out |= bytes[1];
	return out;
}

uint32_t get_u32(const uint8_t *bytes) {
	uint32_t out = 0;
	for (uint8_t i = 0; i < 4; i++) {
		out |= bytes[i];
		if (i < 3) {
			out <<= 8u;
		}
	}
	return out;
}

uint64_t get_u64(const uint8_t *bytes) {
	uint64_t out = 0;
	for (uint8_t i = 0; i < 8; i++) {
		out |= bytes[i];
		if (i < 7) {
			out <<= 8u;
		}
	}
	return out;
}

void set_u16(uint8_t *bytes, uint16_t value) {
	bytes[0] = (uint8_t) (value >> 8u);
	bytes[1] = (uint8_t) (value & 0xffu);
}

void set_u32(uint8_t *bytes, uint32_t value) {
	bytes[0] = (uint8_t) (value >> 24u);
	bytes[1] = (uint8_t) ((value >> 16u) & 0xffu);
	bytes[2] = (uint8_t) ((value >> 8u) & 0xffu);
	bytes[3] = (uint8_t) (value & 0xffu);
}

void set_u64(uint8_t *bytes, uint64_t value) {
	for (uint8_t i = 0; i < 8; i++) {
		bytes[i] = (uint8_t) ((value >> ((7u - i) * 8u)) & 0xffu);
	}
}

void write_u8(uint8_t *buf, uint8_t value) {
	buf[0] = '0' + (value / 100);
	buf[1] = '0' + ((value / 10) % 10);
	buf[2] = '0' + (value % 10);
	buf[3] = 0;
}

char nibble_to_hex(uint8_t nibble) {
	if (nibble < 10) {
		return '0' + nibble;
	} else {
		return 'a' + (nibble - 10);
	}
}

void write_hex_u8(uint8_t *buf, uint8_t value) {
	buf[0] = nibble_to_hex(value & 0xffu);
	buf[1] = nibble_to_hex(value >> 4u);
	buf[2] = 0;
}
